<template>
  <div class="templateManagement" id="templateManagement">
    <div :class="isOpenSide ? 'side-left side-close' : 'side-left'" @mouseenter="mouseenter" @mouseleave="mouseleave">
      <div class="treeBox">
        <div class="buts bottom">
          <a-button class="addButton" type="primary" :disabled="!btnPerm.includes('importAble')" @click="importRecord">
            <template #icon>
              <span class="iconfont icon-Add iconadd"></span>
            </template>
            导入
          </a-button>
          <a-button class="addButton" type="primary" :disabled="!btnPerm.includes('exportAble')" @click="deriveRecord">
            <template #icon>
              <span class="iconfont icon-Add iconadd"></span>
            </template>
            导出
          </a-button>
        </div>

        <!-- <div class="treeTitle">
          <div>
            <div class="openorclose" @click="openorclose" v-show="!isOpen">
              <span>全部收起</span>
              <i class="iconfont icon-up" style="font-size: 24px"> </i>
            </div>
            <div class="openorclose" @click="openorclose" v-show="isOpen">
              <span>全部展开</span>
              <i class="iconfont icon-down" style="font-size: 24px"> </i>
            </div>
          </div>
        </div> -->

        <!-- <base-tree
          :treeData="gData"
          :fieldNames="fieldNames"
          :checkStrictly="false"
          :selectable="true"
          :checkable="false"
          @checked_Keys="checked_Keys"
        ></base-tree> -->
        <a-tree v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys" :load-data="onLoadData"
          :show-line="false" show-icon="false" :tree-data="gData" v-if="gData.length" :fieldNames="fieldNames"
          @select="checked_Keys">
          <template #switcherIcon="{ dataRef, defaultIcon }">
            <img src="@/assets/imgs/folderOpen.png" alt="" srcset="" v-if="!dataRef.fileFlag" />
            <component :is="defaultIcon" v-else />
          </template>
          <template #title="record">
            <div :class="record.fileFlag && 'iconys'">
              <i class="iconfont icon-a-filewenjian" v-if="record.fileFlag" style="margin-left: -12px"></i>
              <span>{{ record.name }}</span>
            </div>
          </template>
        </a-tree>
      </div>
      <div :class="isOpenSide ? 'open-right open-right-side' : 'open-right'" v-show="isShowIcon" @click="openorhideSide">
        <i v-if="isOpenSide" class="iconfonts iconfont icon-a-doubleright" style="font-size: 20px">
        </i>
        <i v-else class="iconfonts iconfont icon-a-doubleleft" style="font-size: 20px">
        </i>
      </div>
    </div>
    <div class="myResourcesRight">
      <div class="buts">
        <a-button class="addButton" type="primary" @click="deleteSelectedAll"
          :disabled="disabled || !btnPerm.includes('deleteAble')">
          删除
        </a-button>
        <a-button class="addButton upload" type="primary" :disabled="!btnPerm.includes('uploadAble')"
          @click="uploadRecord" v-if="IsUpload">
          上传
        </a-button>
        <a-button class="addButton upload" type="primary"
          @click="downloadTpls" v-if="IsUpload && !disabled">
          下载
        </a-button>
        <a-button class="addButton1" type="primary" :disabled="!btnPerm.includes('creatAble')" @click="newRecord">
          新建目录
        </a-button>
      </div>

      <baseTable :columns="columns.templatesColumns" :dataSource="resData" :isSelect="true" :scroll="scroll"
        ref="tagBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
        @deleteRecord="deleteSelectedAll" disabledParam="status" align="middle">
        <template #bodyCell="{ column, text, record, index }">
          <template v-if="column.dataIndex === 'name'">
            <a @click="detailreferRecord(record)" v-if="record.fileFlag" class="fileFlags">
              <i class="iconfont icon-a-filewenjian" v-if="record.fileFlag" style="color:rgba(0,0,0,0.85)"></i>

              <span class="fileName" v-if="text.length < 28"> {{ text }} </span>
              <a-tooltip v-else>
                <template #title>{{ text }}</template>
                <span class="fileName"> {{ text }} </span>
              </a-tooltip>
            </a>
            <a v-else @click="fetchTemplateRightList(record.relativePath)" class="fileFlags">
              <img src="@/assets/imgs/folderOpen.png" alt="" srcset="" />
              <span class="fileName">{{ text }}</span>
            </a>
          </template>
          <template v-if="column.dataIndex === 'oparation'">
            <!-- <a class="eidtRecords" :class="{ disable: !IsUpload || !showDownBtn || record.tplSource !== '低代码编辑器' }"
              @click="uploadEditor(record)">可视化编辑</a> -->
            <a class="eidtRecords" :class="{ disable: !btnPerm.includes('lookReferenceAble') }"
              @click="referRecord(record)">查看引用</a>
            <a class="eidtRecords" :class="{ disable: !btnPerm.includes('deleteAble') }"
              @click="deleteRecord(record)">删除</a>
          </template>
        </template>
      </baseTable>
    </div>
    <templatemodel v-if="isVisible" :isVisible="isVisible" @handleCancle="handleCancle" @handleOk="handleOk"
      :relativePath="IsUpload" :tokenStr="tokenStr" :modelType="modelType" :rowSelection="rowSelection"></templatemodel>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, reactive, onMounted, onBeforeUnmount, nextTick, createVNode } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import baseTree from "@/components/tree/baseTree.vue";
import templatemodel from "./templateModel.vue";
import { scrollType } from "@/type.d";
import { getTableScroll } from "@/components/table/tableConfig/table";
import columns from "@/components/table/tableConfig/tableColumn/configTableColumn";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { dataSourceType, detailDataItemType } from "@/type";
import { Modal, message } from "ant-design-vue";
import type { TreeProps } from "ant-design-vue";
import request from "@/api/index";
import getters from "@/store/getters";
import { randomWord } from "@/utils/common";
import { useRouter, useRoute } from "vue-router";
import { CarryOutOutlined, SmileTwoTone } from "@ant-design/icons-vue";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import { routerPerm } from '@/utils/common';
import { decrypt3DES, encrypt3DES } from "@/utils/cryptojs";
const btnPerm = ref<any[]>([]);
const tabsList = [
  {
    tabName: "内容列表",
    key: 1,
  },
  {
    tabName: "归档列表",
    key: 2,
  },
];
//树结构数据
const fieldNames = reactive<dataSourceType>({
  title: "name",
  key: "relativePath",
});
//interface
interface DataList {
  [propName: string | number]: any;
};
interface Options {
  [propName: string | number]: any;
};

const showDownBtn = ref<any>(false)
const isOpenSide = ref<boolean>(false);
const isShowIcon = ref<boolean>(false);
const expandedKeys = ref<(string | number)[]>([]);
const selectedKeys = ref<string[]>([]);
const gData = ref<any[]>([]);
const resData = ref<(string | number)[]>([]);
// const gData = ref<DataList>([]);
const dataList: TreeProps["treeData"] = [];
const isOpen = ref<boolean>(true); //是否展开或收起.
const isShowPagination = ref<boolean>(false); // 是否需要配分页器

// const renameType = ref<boolean>(false); //重命名输入框
const showCheckDelete = false; // 是否需要分页器中的自定义
const isVisible = ref<boolean>(false); //移动弹窗
const modelType = ref<number>();
let IsUpload = ref<any>("");
const router = useRouter();
const route = useRoute()
let acceptTypeList = ref<string[]>([]);
const tagBaseTables = ref<any>(null);; //
let disabled = ref<any>(true)
//表格数据
let scroll: scrollType = reactive({ y: "", isFixed: false });
nextTick(() => {
  let obj = getTableScroll(74, "contentList", 132);
  scroll.y = obj.y;
  scroll.isFixed = obj.isFixed;
});
let rowSelection = ref<any>(null);
const tokenStr = ref<any>();

//获取栏目层级树列表
const fetchTemplateLeftLazyTree = async (val: any) => {
  let data = await request.fetchTemplateLeftLazyTree({ parentRelativePath: val });
  gData.value = [];
  nextTick(() => {
    gData.value = data;
    // isLeaf
    gData.value.forEach((item: any) => {
      item.isLeaf = item.fileFlag;
      if (!item.fileFlag) {
        item.children = null;
      }
    });
    if (gData.value.length) {
      selectedKeys.value = selectedKeys.value.length ? selectedKeys.value : [gData.value[0].relativePath];
      IsUpload.value = selectedKeys.value[0];
      console.log(IsUpload.value, 'IsUpload.value')
      // localStorage.relativePath =  IsUpload.value
    }
    fetchTemplateRightList(selectedKeys.value['0']);
    dataList.push(...data);
  })

};
//获取模板管理列表
const fetchTemplateRightList = async (val: any) => {
  IsUpload.value = val;
  if(val && val.includes('specialTopic') && val.length > 13 && val.endsWith('specialTopic')) {
    localStorage.relativePath =  val
    showDownBtn.value = true
  }else {
    // localStorage.removeItem('relativePath')
    showDownBtn.value = false
  }
  let data = (await request.fetchTemplateRightList({ parentRelativePath: val })) || [];
  // nextTick(() => {
  //   selectedKeys.value = [val];
  // });
  nextTick(() => {
    data.forEach((item: dataSourceType) => {
      item.id = item.relativePath
      item.tplSource = item.tplSource === 1 ? 'CMS平台' : item.tplSource === 2 ? '低代码编辑器' : ''
    })
    resData.value = data;

  })

};
const onLoadData = (treeNode: DataList) => {
  console.log(treeNode, ' treeNode')
  return new Promise((resolve) => {
    if (treeNode.dataRef.children) {
      resolve(true);
      return;
    }
    setTimeout(async () => {
      let arr =
        (await request.fetchTemplateLeftLazyTree({
          parentRelativePath: treeNode.dataRef.relativePath,
        })) || [];
      arr.forEach((item: any) => {
        item.isLeaf = item.fileFlag;

        if (!item.fileFlag) {
          item.children = null;
        }
      });
      treeNode.dataRef.children = arr;
      gData.value = [...gData.value];
      resolve(true);
    }, 40);
  });
};
const parentKey = ref<(string | number)[]>([]);
const openorclose = () => {
  isOpen.value = !isOpen.value;
  if (isOpen.value) {
    expandedKeys.value = [];
  } else {
    traversal(dataList);
  }
};
const traversal = (data: any) => {
  data.map((item: any) => {
    parentKey.value.push(item.id);
    if (item.children) {
      traversal(item.children);
    }
  });
  expandedKeys.value = parentKey.value;
};
//展开收起侧边栏
const openorhideSide = () => {
  isOpenSide.value = !isOpenSide.value;
};

//侧边栏鼠标移入事件
const mouseenter = () => {
  isShowIcon.value = true;
};

//侧边栏鼠标移出事件
const mouseleave = () => {
  isShowIcon.value = isOpenSide.value ? true : false;
};
// 选中则边栏

const checked_Keys = async (obj: any, info: any) => {
  tagBaseTables.value.selectedRowKeys = [] // 清空复选框
  if (!info.selectedNodes[0]?.fileFlag) {
    obj.length ? fetchTemplateRightList(obj) : '';
  } else {
    info.selectedNodes[0] ? detailreferRecord(info.selectedNodes[0]) : '';
    obj.length ? fetchTemplateRightList(obj) : '';
  }
  nextTick(() => {
    selectedKeys.value[0] = obj[0] || selectedKeys.value[0];
    IsUpload.value = selectedKeys.value[0];
    console.log(IsUpload.value, 'IsUpload.value2222');
    if(IsUpload.value && IsUpload.value.includes('specialTopic') && IsUpload.value.length > 13 && IsUpload.value.endsWith('specialTopic')) {
      localStorage.relativePath =  IsUpload.value
      showDownBtn.value = true
    }else {
      localStorage.removeItem('relativePath')
      showDownBtn.value = false
      }
  })
};
// 导入
const importRecord = () => {
  isVisible.value = true;
  modelType.value = 1;
};
// 导出
const deriveRecord = () => {
  isVisible.value = true;
  modelType.value = 2;
};
//上传
const uploadRecord = () => {
  isVisible.value = true;
  modelType.value = 3;
};
// 下载
const downloadTpls = () => {
  isVisible.value = true;
  modelType.value = 10;
};
// 新建目录
const newRecord = () => {
  isVisible.value = true;
  modelType.value = 4;
};
// 下载模版
const downloadTemplate = () => {
  sessionStorage.removeItem('relativePaths');
  isVisible.value = true;
  modelType.value = 6;
};
// 登录编辑器
const goEditor = () => {
  window.open('http://v.jeecms.com/')
};
// 上传编辑器(单个)
const uploadEditor = (data: any = null) => {
  console.log(data.tplSource,'data.tplSource');
  if(!showDownBtn.value || data.tplSource !== '低代码编辑器') return
  const relativePathList: any[] = []
  relativePathList.push(data.relativePath)
  sessionStorage.setItem('relativePaths', JSON.stringify(relativePathList))
  console.log(JSON.parse(sessionStorage.relativePaths),'sessionStorage.relativePaths');
  isVisible.value = true;
  modelType.value = 8;
};
// 上传编辑器(多个)
const uploadEditorAll = () => {
  console.log(tagBaseTables.value.selectedRowKeys,'tagBaseTables.value.selectedRowKeys');
  console.log(resData.value,'resData.value');
  const arr: any[] = []
  tagBaseTables.value.selectedRowKeys.forEach((i: any) => {
    resData.value.forEach((item: any) => {
      if(i === item.relativePath) {
        arr.push(item)
      }
    })
  })
  const tempType =  arr.every((item: any) => item.tplSource === '低代码编辑器')
  console.log(tempType,'tempType');
  if(!tempType) {
    return message.error('仅支持上传低代码编辑器的模版！')
  }
  sessionStorage.setItem('relativePaths', JSON.stringify(tagBaseTables.value.selectedRowKeys))
  isVisible.value = true;
  modelType.value = 7;
};
// 查看引用
const referRecord = (data: any) => {
  if (!btnPerm.value.includes('lookReferenceAble')) return
  isVisible.value = true;
  modelType.value = 5;
  IsUpload.value = data.relativePath;
};
// 详情
const detailreferRecord = (data: any) => {
  const backgFix = data.name.substring(data.name.lastIndexOf(".") + 1); //获取文件的后缀
  let isFileType = true;
  if (acceptTypeList.value.length) {
    isFileType = acceptTypeList.value.includes(backgFix);

    if (isFileType) {
      router.push({
        path: "/config/templateManagement/detail",
        query: {
          val: data.relativePath,
          name: data.name,
        },
      });
    }
  }
};
// /config/templateManagement/detail
// 删除
const deleteRecord = (data: any) => {
  if (!btnPerm.value.includes('deleteAble')) return
  Modal.confirm({
    content: "是否确认删除？删除后将导致有关联数据无法正常访问",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      request
        .fetchTemplateDeleteBatch({
          relativePathList: [data.relativePath],
        })
        .then((res: any) => {
          if (res.code == "00000 00000") {
            fetchTemplateRightList(IsUpload.value);
            message.success(res.message);
            tagBaseTables.value.selectedRowKeys = [] // 清空复选框
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
        });
    },
    onCancel() { },
  });
};
// 多选删除
// computed
rowSelection = computed(() => {
  return tagBaseTables.value?.selectedRowKeys;
});
nextTick(() => {
  watch(() => tagBaseTables.value?.selectedRowKeys, (newVal, oldVal) => {
    if (newVal && newVal.length < 1) {
      disabled.value = true
    } else {
      disabled.value = false
    }
  })
})
//删除已选所有模型
const deleteSelectedAll = async () => {
  let keys = rowSelection.value;
  Modal.confirm({
    content: "是否确认删除？删除后将导致有关联数据无法正常访问",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      request
        .fetchTemplateDeleteBatch({
          relativePathList: [...keys],
        })
        .then((res: any) => {
          if (res.code == "00000 00000") {
            fetchTemplateRightList(IsUpload.value);
            message.success(res.message);
            tagBaseTables.value.selectedRowKeys = [] // 清空复选框
          } else {
            message.error(res.message); IsUpload
          }
        })
    },
    onCancel() { },
  });
};

const rotateWordTree = (e: any) => {
  console.log(e, "e");
};
const handleOk = () => {
  isVisible.value = false;
  gData.value = [];
  tagBaseTables.value.selectedRowKeys = [] // 清空复选框
  fetchTemplateLeftLazyTree("");
  console.log(selectedKeys, 'selectedKeys')
};
// 关闭弹窗
const handleCancle = () => {
  isVisible.value = false;
};
acceptTypeList = computed({
  get() {
    return ["html", "vue", "js", "css"];
  },
  set() { },
});
const uploadAndGoEdit = () => {
  const list = JSON.parse(sessionStorage.relativePaths)
  const params = {
    lowCodeToken: sessionStorage.ken,
    relativePaths: list
  }
  // console.log(params,'params');
  
  request.fetchUploadEdit(params).then((res: any)  => {
    console.log(res,'res');
    if(res.code === "00000 00000") {
      message.success(res.message)
      window.open('http://v.jeecms.com/')
    }else {
      message.error(res.message)
    }
  }).catch((err: any) => {
    throw new Error(err)
  })
};
// 低代码跳转回来之后
const getToken = () => {
  const urlStr: any = sessionStorage.ken
  console.log(urlStr,'urlStr');
  if(urlStr) {
    if(sessionStorage.relativePaths) {
      // 上传编辑器
      uploadAndGoEdit()
    console.log('跳转到编辑器',urlStr);
    }else {
    console.log('下载模版', urlStr);
    tokenStr.value = urlStr
    modelType.value = 6;
    showDownBtn.value = true
    isVisible.value = true
    }
  }
};

//onmounted
onMounted(() => {
  showDownBtn.value = false
  getToken();
  btnPerm.value = routerPerm();
  fetchTemplateLeftLazyTree("");

  // fetchResourceGroupAdd();
});

onBeforeUnmount(() => {
  sessionStorage.removeItem('ken')
})

</script>

<style lang="less" scoped>
.templateManagement {
  width: 100%;
  // background: #fff;
  // padding-bottom: 24px;
  height: calc(100% - 72px);
  display: flex;
  background-color: #fff;
  padding: 16px;

  .side-left {
    width: 216px;
    height: calc(100% - 24px);
    border-right: 1px solid rgba(0, 0, 0, 0.06);
    padding-right: 4px;
    position: relative;
    transition: width 0.3s;
    padding-right: 16px;

    .iconys {
      transform: translateX(-10px);

      i {
        color: rgb(153, 153, 153);
      }

      span {
        margin-left: 4px;
      }
    }

    .res-tree-menus {
      margin: 0;
      background: #fff;
      z-index: 44;
      position: absolute;
      list-style-type: none;
      min-width: 130px;
      padding: 5px 0;
      box-sizing: border-box;
      border-radius: 4px;
      box-shadow: 0px -3px 16px 0px rgba(89, 155, 255, 0.15);

      li {
        margin: 0;
        padding: 0 20px;
        cursor: pointer;
        font-size: 14px;
        font-weight: 400;
        line-height: 32px;
        color: rgba(0, 0, 0, 0.85);

        &:hover {
          background: rgba(0, 0, 0, 0.04);
        }
      }
    }

    .treeBox {
      height: 100%;
    }

    .treeTitle {
      margin-top: 16px;
      margin-bottom: 4px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 24px;
      background: #edf7ff;
      border-radius: 2px;
      padding: 0 4px;

      .openorclose {
        cursor: pointer;
        display: flex;
        align-items: center;
      }
    }

    .open-right {
      position: absolute;
      top: 50%;
      right: -1px;
      margin-top: -15px;
      bottom: -20px;
      height: 30px;
      width: 20px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      background: #ffffff;
      border: 1px solid rgba(0, 0, 0, 0.06);
      z-index: 2;
    }

    .open-right-side {
      right: -20px;
    }

    .iconfont:hover {
      color: rgba(0, 0, 0, 0.6);
    }

    .iconfonts {
      color: rgba(0, 0, 0, 0.45);
    }
  }

  .side-close {
    width: 0;
    transition: width 0.3s;

    .treeBox {
      display: none;
    }
  }

  .myResourcesRight {
    width: 500px;
    border-left: 1px solid rgba(0, 0, 0, 0.06);
    flex: 1;
    height: 100%;
    padding-left: 16px;
  }

  .buts {
    display: flex;

    .addButton:last-child {
      margin-left: 16px;
    }
    .addButton1 {
      margin-left: 16px;
    }

    .upload {
      margin-left: 16px;
    }
  }

  .bottom {
    margin-bottom: 7px;
  }

  :deep(.ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    padding-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }

  .eidtRecords:last-child {
    margin-right: 0;
  }

  ::v-deep(.titleBox) {
    display: flex;
    align-items: center;
    justify-items: center;

    // height: 29px;
    // line-height: 29px;
    // height: 18px;
    .titleTip {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-left: 16px;
    }

    .tabletypeImgBox {
      width: 80px;
      height: 80px;
      padding: 8px;
      background: #ffffff;
      border-radius: 2px;
      border: 1px solid rgba(0, 0, 0, 0.15);
    }

    .tabletypeImg {
      max-width: 64px;
      width: auto;
      max-height: 64px;

      height: auto;
      margin: auto;
      //   width: 16px;
      //   height: 16px;
      // line-height: 18px;
    }
  }

  ::v-deep(.ant-table-cell) {
    vertical-align: middle;
  }
}

.icon-a-Folder-openwenjianjia-kai {
  color: #ffca28;
}

.contentIndexLeft {
  padding-right: 24px;
  width: 216px;
  height: 100%;
}

::v-deep(::-webkit-scrollbar) {
  height: 10px;
}

::v-deep(.side-left .ant-tree-list-holder) {
  width: auto;
  height: 100%;
  transition: width 0.3s;
}

::v-deep(.side-close .ant-tree-list-holder) {
  width: 0;
  height: 100%;
  transition: width 0.3s;
}

::v-deep(.side-left .ant-tree-list:hover .ant-tree-list-scrollbar) {
  display: block !important;
}

::v-deep(.ant-tree-list .ant-tree-list-scrollbar) {
  display: none !important;
}

::v-deep(.ant-tree-list-scrollbar-thumb) {
  background: rgba(0, 0, 0, 0.15) !important;
}

::v-deep(.ant-checkbox + span) {
  padding-left: 12px;
  padding-right: 0;
}

::v-deep(.ant-table-wrapper) {
  margin-top: 16px;
}

::v-deep(.ant-table-thead > tr > th) {
  // padding: 16px 0 16px 16px;
}

table tr th.ant-table-selection-column,
table tr td.ant-table-selection-column {
  padding-right: 8px;
  padding-left: 8px;
  text-align: left;
}
</style>
<style lang="less">
.side-left {
  .ant-input-search {
    margin-top: 16px;
  }

  .ant-tree {
    height: calc(100% - 88px);
    overflow: auto;

    .ant-tree-treenode {
      width: 100%;

      .ant-tree-node-content-wrapper {
        width: 100%;
      }
    }

    .ant-tree::-webkit-scrollbar {
      display: none;
    }

    .ant-tree:hover::-webkit-scrollbar {
      display: block;
    }

    .ant-tree-list-scrollbar-thumb {
      height: auto !important;
    }

    .ant-tree-list-holder {
      overflow-y: unset !important;
    }
  }
}

.fileFlags {
  display: flex;
  align-items: center;

  .iconfont {
    margin-right: 4px;
  }

  img {
    margin-right: 4px;
  }
}

.fileName {
  max-width: 260px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
